package cn.lblbc.album

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.album.adapter.ImageAdapter
import cn.lblbc.album.utils.ImageLoader
import cn.lblbc.album.utils.PermissionHelper
import com.google.android.material.button.MaterialButton

class MainActivity : AppCompatActivity() {
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var permissionLayout: View
    private lateinit var requestPermissionButton: MaterialButton
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        
        initViews()
        setupWindowInsets()
        requestStoragePermission()
    }
    
    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerView)
        permissionLayout = findViewById(R.id.permissionLayout)
        requestPermissionButton = findViewById(R.id.requestPermissionButton)
        
        // 设置网格布局，每行显示2张图片
        recyclerView.layoutManager = GridLayoutManager(this, 2)
        
        requestPermissionButton.setOnClickListener {
            requestStoragePermission()
        }
        
        // 默认隐藏权限请求布局，让图片视图可见
        permissionLayout.visibility = View.GONE
        recyclerView.visibility = View.VISIBLE
    }
    
    private fun setupWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
    
    private fun checkPermissions() {
        if (PermissionHelper.hasStoragePermission(this)) {
            showImageGallery()
        } else {
            showPermissionRequest()
        }
    }
    
    private fun autoLoadImages() {
        // 直接尝试加载图片，即使没有明确权限
        showImageGallery()
    }
    
    private fun showImageGallery() {
        permissionLayout.visibility = View.GONE
        recyclerView.visibility = View.VISIBLE
        
        // 加载图片
        val images = ImageLoader.loadImages(this)
        
        // 总是设置适配器，即使图片列表为空
        val adapter = ImageAdapter(images)
        recyclerView.adapter = adapter
        
        // 只有在图片为空时才显示提示
        if (images.isEmpty()) {
            Toast.makeText(this, R.string.no_images_found, Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun showPermissionRequest() {
        recyclerView.visibility = View.GONE
        permissionLayout.visibility = View.VISIBLE
        
        if (PermissionHelper.shouldShowRequestPermissionRationale(this)) {
            Toast.makeText(this, "相册需要访问您的照片权限才能正常工作", Toast.LENGTH_LONG).show()
        }
    }
    
    private fun requestStoragePermission() {
        PermissionHelper.requestStoragePermission(this)
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == 100) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                showImageGallery()
            } else {
                // 如果权限被拒绝，仍然尝试显示图片（有些设备可能不需要权限）
                showImageGallery()
                // 如果图片列表为空，再显示权限请求界面
                val images = ImageLoader.loadImages(this)
                if (images.isEmpty()) {
                    Toast.makeText(this, "权限被拒绝，无法显示图片", Toast.LENGTH_SHORT).show()
                    showPermissionRequest()
                }
            }
        }
    }
}